package com.night.xjh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.night.common.entity.card.Card;
import com.night.common.entity.xjh.Visit;
import com.night.xjh.mapper.VisitMapper;
import com.night.xjh.service.VisitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: VisitServiceImpl
 * @Description: //TODO
 * @author: xjh
 * @date: 2022/10/21-11:02
 * @version: v1.0
 */
@Service
public class VisitServiceImpl implements VisitService {
    @Resource
    private VisitMapper visitMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void add(Visit visit) {
        visitMapper.add(visit);
    }

    public void delete(int id) {
        visitMapper.deleteById(id);
    }

    public void update(Visit visit) {
        visitMapper.update(visit);
    }

    @Override
    public PageInfo<Visit> getByDate(String startDate,String endDate, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        String redisName="getByDate-startDate-"+startDate+"+endDate-"+endDate+"+pageNum-"+pageNum+"+pageSize-"+pageSize;
        List<Visit> redisVisit = (List<Visit>) redisTemplate.opsForValue().get(redisName);
        if(redisVisit!=null){
            return new PageInfo<>(redisVisit);
        }
        List<Visit> list=visitMapper.getByDate(startDate,endDate);
        redisTemplate.opsForValue().set(redisName, list, 20, TimeUnit.SECONDS);
        return new PageInfo<>(list);
    }

    public PageInfo<Visit> getAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Visit> redisVisit = (List<Visit>) redisTemplate.opsForValue().get("visit-getAll");
        if (redisVisit != null)
            return new PageInfo<>(redisVisit);
        List<Visit> list=visitMapper.getAll();
        redisTemplate.opsForValue().set("visit-getAll", list, 30, TimeUnit.SECONDS);
        return new PageInfo<>(list);
    }

    public Visit getById(int id) {
        return visitMapper.getById(id);
    }

    public PageInfo<Visit> getByCondition(Visit visit, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        String redisName="getByCondition-visitDate-"+visit.getVisitDate()+"+pageNum-"+pageNum+"+pageSize-"+pageSize;
        List<Visit> redisVisit = (List<Visit>) redisTemplate.opsForValue().get(redisName);
        if(redisVisit!=null){
            return new PageInfo<>(redisVisit);
        }
        List<Visit> list=visitMapper.getByCondition(visit);
        redisTemplate.opsForValue().set(redisName, list, 30, TimeUnit.SECONDS);
        return new PageInfo<>(list);
    }
}
